import 'dart:async';

import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:macnov/utils/event_bus.dart';
import 'package:macnov/utils/http_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TokenInterceptor extends Interceptor {
  @override
  Future onRequest(RequestOptions options) {
    Dio _dio = HttpManager().getDio();
    _dio.lock();
    Future<dynamic> future = Future(() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      return prefs.getString("token");
    });
    return future.then((value) {
      options.headers["authorization"] = value ?? '';
      return options;
    }).whenComplete(() => _dio.unlock()); // unlock the dio
  }

  @override
  Future onResponse(Response response) {
    return super.onResponse(response);
  }

  @override
  Future onError(DioError err) {
    return super.onError(err);
  }
}

class BytesRespInterceptor extends Interceptor {
  @override
  Future onRequest(RequestOptions options) {
    options.responseType = ResponseType.bytes;
    return super.onRequest(options);
  }

  @override
  Future onResponse(Response response) {
    return super.onResponse(response);
  }

  @override
  Future onError(DioError err) {
    return super.onError(err);
  }
}

class JsonContentTypeInterceptor extends Interceptor {
  @override
  Future onRequest(RequestOptions options) {
    options.headers["Content-Type"] = 'application/json';
    return super.onRequest(options);
  }

  @override
  Future onResponse(Response response) {
    return super.onResponse(response);
  }

  @override
  Future onError(DioError err) {
    return super.onError(err);
  }
}

class ErrorInterceptor extends Interceptor {
  @override
  Future onError(DioError err) {
    if (null != err.response) {
      if (err.response.statusCode == 401) {
        eventBus.fire(LoginEvent());
      } else {
        Fluttertoast.showToast(
            msg: err.message,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIos: 1,
            fontSize: 16.0);
      }
    } else if (null != err.request) {
      // network error
    }
    return super.onError(err);
  }
}
